<template>
  <div class="interview-detail-container">
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-button @click="handleBack" class="back-btn">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <div class="title-section">
            <h1 class="page-title">面试详情</h1>
            <div class="page-subtitle" v-if="interviewData">
              {{ interviewData.title }}
            </div>
          </div>
        </div>
        <div class="header-actions" v-if="interviewData">
          <el-tag :type="getStatusTagType(interviewData.status)" size="large">
            {{ getStatusText(interviewData.status) }}
          </el-tag>
        </div>
      </div>
    </div>

    <div class="page-content" v-loading="loading">
      <div v-if="interviewData" class="detail-content">
        <!-- 基本信息卡片 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <el-icon><InfoFilled /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          
          <div class="info-grid">
            <div class="info-item">
              <label>面试标题</label>
              <span>{{ interviewData.title }}</span>
            </div>
            <div class="info-item">
              <label>面试类型</label>
              <el-tag :type="getTypeTagType(interviewData.interview_type)" size="small">
                {{ getTypeText(interviewData.interview_type) }}
              </el-tag>
            </div>
            <div class="info-item">
              <label>学生姓名</label>
              <span>{{ interviewData.student_name }}</span>
            </div>
            <div class="info-item">
              <label>面试官</label>
              <span>{{ interviewData.interviewer_name }}</span>
            </div>
            <div class="info-item">
              <label>预定时间</label>
              <span>{{ formatTimeRange(interviewData.scheduled_time, interviewData.scheduled_end_time) }}</span>
            </div>
            <div class="info-item">
              <label>面试地点</label>
              <span>{{ interviewData.location || '未指定' }}</span>
            </div>
          </div>
        </el-card>

        <!-- 时间信息卡片 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <el-icon><Clock /></el-icon>
              <span>时间信息</span>
            </div>
          </template>
          
          <div class="time-info">
            <div class="time-item">
              <div class="time-label">预定时间段</div>
              <div class="time-value">{{ formatTimeRange(interviewData.scheduled_time, interviewData.scheduled_end_time) }}</div>
            </div>
            <div class="time-item" v-if="interviewData.actual_start_time">
              <div class="time-label">实际开始</div>
              <div class="time-value">{{ formatDateTime(interviewData.actual_start_time) }}</div>
            </div>
            <div class="time-item" v-if="interviewData.actual_end_time">
              <div class="time-label">实际结束</div>
              <div class="time-value">{{ formatDateTime(interviewData.actual_end_time) }}</div>
            </div>
            <div class="time-item" v-if="getDuration(interviewData)">
              <div class="time-label">面试时长</div>
              <div class="time-value">{{ getDuration(interviewData) }}</div>
            </div>
          </div>
        </el-card>

        <!-- 面试描述 -->
        <el-card class="info-card" shadow="never" v-if="interviewData.description">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>面试描述</span>
            </div>
          </template>
          
          <div class="description-content">
            {{ interviewData.description }}
          </div>
        </el-card>

        <!-- 评分和反馈 -->
        <el-card class="info-card" shadow="never" v-if="interviewData.overall_score || interviewData.feedback">
          <template #header>
            <div class="card-header">
              <el-icon><Star /></el-icon>
              <span>评分反馈</span>
            </div>
          </template>
          
          <div class="feedback-content">
            <div class="score-section" v-if="interviewData.overall_score">
              <div class="score-label">总体评分</div>
              <div class="score-value">
                <el-rate 
                  :model-value="interviewData.overall_score" 
                  disabled 
                  show-score 
                  text-color="#ff9900"
                />
              </div>
            </div>
            <div class="feedback-section" v-if="interviewData.feedback">
              <div class="feedback-label">面试反馈</div>
              <div class="feedback-text">{{ interviewData.feedback }}</div>
            </div>
            <div class="suggestions-section" v-if="interviewData.suggestions">
              <div class="suggestions-label">改进建议</div>
              <div class="suggestions-text">{{ interviewData.suggestions }}</div>
            </div>
          </div>
        </el-card>

        <!-- 操作按钮 -->
        <div class="action-section" v-if="showActions">
          <el-button 
            v-if="canStartInterview" 
            type="primary" 
            @click="handleStartInterview"
            :loading="actionLoading"
          >
            开始面试
          </el-button>
          <el-button 
            v-if="canCompleteInterview" 
            type="success" 
            @click="handleCompleteInterview"
            :loading="actionLoading"
          >
            完成面试
          </el-button>
          <el-button 
            v-if="canViewResult" 
            type="info" 
            @click="handleViewResult"
          >
            查看结果
          </el-button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!loading" class="empty-state">
        <el-empty description="未找到面试信息" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, InfoFilled, Clock, Document, Star
} from '@element-plus/icons-vue'
import { interviewApi } from '@/api/interview'
import { formatDateTime } from '@/utils/format'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const actionLoading = ref(false)
const interviewData = ref(null)

// 计算属性
const userRole = computed(() => userStore.userInfo?.role)
const isTeacher = computed(() => ['admin', 'teacher'].includes(userRole.value))

const showActions = computed(() => {
  return isTeacher.value && interviewData.value
})

const canStartInterview = computed(() => {
  return interviewData.value?.status === 'scheduled'
})

const canCompleteInterview = computed(() => {
  return interviewData.value?.status === 'in_progress'
})

const canViewResult = computed(() => {
  return interviewData.value?.status === 'completed'
})

// 方法
const handleBack = () => {
  router.back()
}

const getStatusTagType = (status) => {
  const statusMap = {
    'scheduled': 'warning',
    'in_progress': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    'expired': 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'scheduled': '已安排',
    'in_progress': '进行中',
    'completed': '已完成',
    'cancelled': '已取消',
    'expired': '已过期'
  }
  return statusMap[status] || status
}

const getTypeTagType = (type) => {
  const typeMap = {
    'practice': 'success',
    'mock': 'primary',
    'assessment': 'warning',
    'career_guidance': 'info'
  }
  return typeMap[type] || 'info'
}

const getTypeText = (type) => {
  const typeMap = {
    'practice': '练习面试',
    'mock': '模拟面试',
    'assessment': '评估面试',
    'career_guidance': '职业指导'
  }
  return typeMap[type] || type
}

const formatTimeRange = (startTime, endTime) => {
  if (!startTime) return '未安排'

  const start = formatDateTime(startTime)
  if (!endTime) return start

  const end = formatDateTime(endTime)

  // 如果是同一天，只显示一次日期
  const startDate = new Date(startTime).toISOString().split('T')[0]
  const endDate = new Date(endTime).toISOString().split('T')[0]

  if (startDate === endDate) {
    const startTimeOnly = new Date(startTime).toTimeString().substring(0, 5)
    const endTimeOnly = new Date(endTime).toTimeString().substring(0, 5)
    return `${startDate} ${startTimeOnly}~${endTimeOnly}`
  }

  return `${start}~${end}`
}

const getDuration = (interview) => {
  if (!interview.actual_start_time || !interview.actual_end_time) return null

  const start = new Date(interview.actual_start_time)
  const end = new Date(interview.actual_end_time)
  const diffMs = end - start
  const diffMins = Math.round(diffMs / 60000)

  if (diffMins < 60) {
    return `${diffMins}分钟`
  } else {
    const hours = Math.floor(diffMins / 60)
    const mins = diffMins % 60
    return `${hours}小时${mins}分钟`
  }
}

const fetchInterviewDetail = async () => {
  const interviewId = route.params.id
  if (!interviewId) {
    ElMessage.error('面试ID无效')
    router.back()
    return
  }

  loading.value = true
  try {
    const response = await interviewApi.getInterviewDetail(interviewId)
    interviewData.value = response.data
  } catch (error) {
    console.error('获取面试详情失败:', error)
    ElMessage.error('获取面试详情失败')
    interviewData.value = null
  } finally {
    loading.value = false
  }
}

const handleStartInterview = async () => {
  try {
    await ElMessageBox.confirm('确认开始面试吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    actionLoading.value = true
    await interviewApi.startInterview(interviewData.value.id)
    ElMessage.success('面试已开始')
    await fetchInterviewDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始面试失败:', error)
      ElMessage.error('开始面试失败')
    }
  } finally {
    actionLoading.value = false
  }
}

const handleCompleteInterview = async () => {
  try {
    await ElMessageBox.confirm('确认完成面试吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    actionLoading.value = true
    await interviewApi.completeInterview(interviewData.value.id)
    ElMessage.success('面试已完成')
    await fetchInterviewDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成面试失败:', error)
      ElMessage.error('完成面试失败')
    }
  } finally {
    actionLoading.value = false
  }
}

const handleViewResult = () => {
  router.push(`/interviews/result/${interviewData.value.id}`)
}

// 生命周期
onMounted(() => {
  fetchInterviewDetail()
})
</script>

<style lang="scss" scoped>
.interview-detail-container {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  transition: background-color 0.3s ease;
}

.page-header {
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  padding: 24px 32px;
  transition: all 0.3s ease;
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    max-width: 1200px;
    margin: 0 auto;
  }
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
  }
  
  .back-btn {
    border: none;
    background: var(--el-bg-color-page);
    color: var(--el-text-color-secondary);
    transition: all 0.3s ease;

    &:hover {
      background: var(--el-color-primary);
      color: white;
    }
  }
  
  .title-section {
    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    .page-subtitle {
      margin-top: 4px;
      color: var(--el-text-color-secondary);
      font-size: 14px;
    }
  }
}

.page-content {
  margin: 0 auto;
  padding: 24px 32px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.info-card {
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  background: var(--el-bg-color);
  transition: all 0.3s ease;

  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
  
  .info-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
    
    label {
      font-weight: 600;
      color: var(--el-text-color-secondary);
      font-size: 14px;
    }

    span {
      color: var(--el-text-color-primary);
      font-size: 16px;
    }
  }
}

.time-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
  
  .time-item {
    text-align: center;
    padding: 16px;
    background: var(--el-bg-color-page);
    border-radius: 8px;
    transition: background-color 0.3s ease;

    .time-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      margin-bottom: 8px;
    }

    .time-value {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
}

.description-content {
  line-height: 1.6;
  color: var(--el-text-color-primary);
  white-space: pre-wrap;
}

.feedback-content {
  .score-section {
    margin-bottom: 24px;
    
    .score-label {
      font-weight: 600;
      color: var(--el-text-color-secondary);
      margin-bottom: 12px;
    }
  }

  .feedback-section,
  .suggestions-section {
    margin-bottom: 24px;

    .feedback-label,
    .suggestions-label {
      font-weight: 600;
      color: var(--el-text-color-secondary);
      margin-bottom: 12px;
    }

    .feedback-text,
    .suggestions-text {
      line-height: 1.6;
      color: var(--el-text-color-primary);
      white-space: pre-wrap;
    }
  }
}

.action-section {
  display: flex;
  gap: 16px;
  justify-content: center;
  padding: 24px 0;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    padding: 16px 20px;
    
    .header-content {
      flex-direction: column;
      gap: 16px;
      align-items: flex-start;
    }
  }
  
  .page-content {
    padding: 16px 20px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .time-info {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .action-section {
    flex-direction: column;
    align-items: center;
  }
}
</style>
